// components/tabs/tabs.js
Component({
	/**
	 * 组件的属性列表
	 */
	options: {
		addGlobalClass: true,
	},
	externalClasses: ['tabs-class'],
	properties: {
		value: {
			type: null,
			value: '',
			observer: function (n, o) {
				this.setData({
					choose: n,
				})
			},
		},
		solid: {
			type: Boolean,
			default: false,
		},
	},
	relations: {
		'../tab/tab': {
			type: 'child', // 关联的目标节点应为子节点
			linked: function (target) {
				// 每次有custom-li被插入时执行，target是该节点实例对象，触发在该节点attached生命周期之后
				// console.log(target)
				// console.log(target.data)
			},
			linkChanged: function (target) {
				// 每次有custom-li被移动后执行，target是该节点实例对象，触发在该节点moved生命周期之后
				// console.log(target)
			},
			unlinked: function (target) {
				// 每次有custom-li被移除时执行，target是该节点实例对象，触发在该节点detached生命周期之后
				// console.log(target)
			},
		},
	},
	/**
	 * 组件的初始数据
	 */
	data: {
		tabList: [],
		tabNodes: [],
		choose: 0,
		x: 0,
		startX: 0,
		endX: null,
	},
	methods: {
		getList() {
			// 使用getRelationNodes可以获得nodes数组，包含所有已关联的custom-li，且是有序的
			var nodes = this.getRelationNodes('../tab/tab')
			let tabList = []
			nodes.map((v, i) => {
				tabList = [...tabList, { ...v.data.tabInfo, index: i }]
			})
			this.setData({ tabList, tabNodes: nodes })
			this.setChoose(this.data.value || 0)
		},
		clickFn(e) {
			let index = e.target.dataset.data.index
			this.setChoose(index)
		},
		startFn(e) {
			this.setData({
				startX: e.touches[0].pageX,
				endX: null,
			})
		},
		moveFn(e) {
			this.setData({
				endX: e.touches[0].pageX,
			})
		},
		endFn(e) {
			if (this.data.endX === null) {
				return
			}
			let moveX = this.data.endX - this.data.startX
			let move = -Math.round(moveX / (this.data.pageWidth * 0.5))
			let index = Number(this.data.choose)
			if (move > 0) {
				index = index + 1
			} else if (move < 0) {
				index = index - 1
			}
			console.log(index)
			if (index < 0 || index > this.data.tabList.length - 1) {
				return
			}
			this.setChoose(index)
		},
		setChoose(index = 0) {
			this.triggerEvent('input', index)
			this.setData({
				value: index,
				x: -index * this.data.pageWidth,
			})
		},
	},
	ready: function () {
		// this.getList()
		this.getList()
		const query = wx.createSelectorQuery()
		query.select('movable-area.tabs-area').boundingClientRect()
		query.selectViewport().scrollOffset()
		query.exec(res => {
			let json = (res || []).filter(v => v)[0] || {}
			// console.log(json)
			this.setData({
				pageWidth: json.scrollWidth,
			})
		})
	},
})
